//
//  MIDIverifyController.m
//  迷笛
//
//  Created by . on 2018/10/9.
//  Copyright © 2018年 🍃🌺🌺🍃. All rights reserved.
//

#import "MIDIverifyController.h"
#import "TPPasswordTextView.h"
#import "ViewController.h"
#import "MIDIlandingController.h"
@interface MIDIverifyController ()

@property(nonatomic,strong)UILabel * phone;
@property(nonatomic,strong)UIButton * seconds;
@property(nonatomic,strong)TPPasswordTextView *view4;
@property(nonatomic,strong)NSString * string;
@property(nonatomic,copy) NSNumber *numTemp;
@property(nonatomic,strong)UIButton * cancel;
@property(nonatomic,strong)NSString * Loing;
@property(nonatomic,strong)NSString * key ;
@property(nonatomic,strong)NSString * midisendSms;
@property(nonatomic,strong)NSString * KEy;
@property(nonatomic,strong)NSString * Code;

@end

@implementation MIDIverifyController
@synthesize str;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self timeOut];
    [self Verification];

    self.navigationController.navigationBar.translucent = NO;//Bar的模糊效果，默认为YES
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    self.view.backgroundColor =[UIColor colorWithHexString:@"#1B212F"];
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:@selector(Block:)];
    self.navigationItem.leftBarButtonItem = leftBarItem;

    [self.navigationItem.leftBarButtonItem setImage:[[UIImage imageNamed:@"chacha"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    [self UIin];
}

//视图将要出现时（导航颜色字体颜色）
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithHexString:@"##171717"];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFFFFF"]}];
    //    去掉导航黑线
    UIImage *img = [UIImage imageNamed:@""];
    [self.navigationController.navigationBar setBackgroundImage:img  forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc]init];
}
-(void)Block:(UIButton * )sender
{
//    固定返回前几个界面
    NSInteger index = (NSInteger)[[self.navigationController viewControllers] indexOfObject:self];
    if (index > 1)//1位界面个数
    {
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:(index-2)] animated:YES];
    }
    else
    {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
-(void)UIin
{
    
    [self.view addSubview:self.cancel];
    [self.cancel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(kDevice_Is_iPhoneX?HeighX(70):HeightScale(30));
        make.left.mas_offset(WidthScale(16));
        make.width.mas_offset(WidthScale(21));
        make.height.mas_offset(HeightScale(21));
    }];
    
    
    [self.view addSubview:self.phone];
    [self.phone mas_makeConstraints:^(MASConstraintMaker *make)
    {
    make.top.mas_offset(kDevice_Is_iPhoneX?HeighX(102):HeightScale(58));
    make.left.mas_offset(WidthScale(36));
    [self.phone setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    }];
    [self.view addSubview:self.seconds];
    [self.seconds mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phone.mas_bottom).offset(WidthScale(20));
        make.left.equalTo(self.phone);
         [self.seconds setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
}];
    [self.view addSubview:self.view4];
    [self.view4 mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.equalTo(self.seconds.mas_bottom).offset(WidthScale(20));
        make.left.equalTo(self.phone);
        make.width.mas_offset(WidthScale(325));
        make.height.mas_offset(kDevice_Is_iPhoneX?HeighX(45):HeightScale(45));
    }];

}
-(UIButton *)cancel
{
    if (!_cancel)
    {
        _cancel =[[UIButton alloc]init];
        [_cancel setBackgroundImage:[UIImage imageNamed:@"chacha"] forState:0];
        [_cancel addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancel;
}
-(void)cancel:(UIButton * )sendre
{
//    多个界面直接掉到一级视图
    [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}
-(UILabel *)phone
{
    if (!_phone)
    {
        _phone =[[UILabel alloc]init];
        _phone.textColor = [UIColor colorWithHexString:@"#FFFFFF"];
        _phone.font =[UIFont systemFontOfSize:WidthScale(16)];
//        _phone.text = @"验证码发送至13956668899";
        NSString *strr = [NSString stringWithFormat:@"验证码发送至%@",str];
        _phone.text = strr;
    }
    return _phone;
}
-(UIButton *)seconds
{
    if (!_seconds)
    {
        _seconds =[[UIButton alloc]init];
        [_seconds setTitle:@"53s后重新发送" forState:0];
        _seconds.titleLabel.font =[UIFont systemFontOfSize:WidthScale(14)];
        [_seconds setTitleColor:[UIColor colorWithHexString:@"#FFFFFF"] forState:0];
        [self.seconds addTarget:self action:@selector(btn:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _seconds;
}
-(TPPasswordTextView *)view4
{
    if (!_view4)
    {
        CGPoint center = self.view.center;
        _view4 = [[TPPasswordTextView alloc]init];

        _view4.elementCount = 4;
        _view4.center = CGPointMake(center.x, 200);
        _view4.elementBorderColor = [UIColor grayColor];
        _view4.elementMargin = 5;
        
        _view4.passwordDidChangeBlock = ^(NSString *password)
        {
            NSLog(@"%@",password);

            self.string = password;
            NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
            [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
            self.numTemp = [numberFormatter numberFromString:self.string];
           
            NSLog(@"短信%@",self.string);
            if (password.length == 4)
            {
                [self Logingrequest];
            }
        
           
        };
    }
    return _view4;
}
-(void)Verification
{
    
    NSString * sendSms = @"sendSms";
    _midisendSms = [NSString stringWithFormat:@"%@%@",MIDIApiRoot,sendSms];
    NSDictionary * parameter =@{@"mobile":str};
    [EdHttp post:_midisendSms params:parameter progress:^(id uploadProgress)
     {
         
     }
         success:^(id responseObject)
     {
         
         NSLog(@"登陆接口%@",responseObject);
         NSDictionary * dic = responseObject[@"data"];
         _KEy = [dic objectForKey:@"key"];
         NSLog(@"KeyKeyKeyKey--%@",_KEy);
         
     }
         failure:^(NSError *error)
     {
         
     }];
}

-(void)Logingrequest
{
    
    NSLog(@"手机号码%@",str);
    NSLog(@"验证码-%@",self.numTemp);
    NSLog(@"key-%@",_KEy);
    
    NSString * typeN = @"n";
    
    NSString * login = @"login";
    _Loing = [NSString stringWithFormat:@"%@app/%@",MIDIApiRoot,login];
    
    
    NSDictionary *Logingparameter = @{@"phone":str,@"verification_code":self.numTemp,@"type":typeN,@"key":_KEy};
    [EdHttp post:_Loing params:Logingparameter progress:^(id uploadProgress)
    {

    }
         success:^(id responseObject)
    {
        NSLog(@"使用验证码%@",responseObject);
        NSDictionary * dic = [responseObject objectForKey:@"data"];
        NSString * Token = [dic objectForKey:@"token"];
        
    
        if ([responseObject[@"code"] isEqualToNumber:@200])
        {
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            [user setObject:Token forKey:@"APPToken"];
            NSLog(@"token%@",Token);

            [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"验证码错误"];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    }
         failure:^(NSError *error)
    {
        NSLog(@"error失败%@",error);
    }];
}

//倒计时方法
- (void)timeOut
{
    __block NSInteger timeOut = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_source_t _Timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //每秒执行一次
    dispatch_source_set_timer(_Timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_Timer, ^{
        if (timeOut <= 0)
        {
            //如果倒计时结束，则关闭
            
            dispatch_source_cancel(_Timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //倒计时结束，关闭之后进行的操作。
                [self.seconds setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [self.seconds setTitle:@"重新发送" forState:UIControlStateNormal];
                self.seconds.userInteractionEnabled = YES;
                
                [self Verification];

                [self Loing];
            });
            
        } else {
            
            int allTime = (int)60 + 1;
            
            int seconds = timeOut % allTime;
            
            NSString *timeStr = [NSString stringWithFormat:@"%0.2d",seconds];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
            //倒计时进行中进行的操作
                
            [self.seconds setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            self.seconds.layer.borderColor = [UIColor redColor].CGColor;
                
            [self.seconds setTitle:[NSString stringWithFormat:@"%@秒后重新发送",timeStr] forState:UIControlStateNormal];
            self.seconds.userInteractionEnabled = NO;
            });
            timeOut--;
        }
    });
    dispatch_resume(_Timer);
}
-(void)btn:(UIButton * )sender
{
    [self timeOut];
}
@end
